import { ref } from 'vue'
import { defineStore } from 'pinia'
import { getIpCity, getWeatherByAdcode } from '@/api/index'

export const useCounterStore = defineStore('counter', () => {
  const ipCity = ref('')
  const weather = ref('')
  // ↑ IP城市名和天气数据
  const adcodeWeather = ref([])
  const lastadcodeWeather = ref([])
  const isShow = ref(true)
  const isShow_1 = ref(true)
  const localstoreCity = ref([])
  const curCity = ref('')
  const curAdcode = ref('')

  const getIpCityData = async () => {
    const { data } = await getIpCity()
    ipCity.value = data.city
    const res = await getWeatherByAdcode(data.adcode)
    weather.value = res.data.forecasts[0].casts
    console.log(weather.value, 'weather-stores')
  }

  const getWeatherData = async (adcode) => {
    const res = await getWeatherByAdcode(adcode)
    adcodeWeather.value.push(res.data.forecasts[0].casts)
    lastadcodeWeather.value = adcodeWeather.value.slice(-1)
    console.log(lastadcodeWeather.value, 'lastadcodeWeather-stores,返回最后一个')
    console.log(adcodeWeather.value.length, 'lastadcodeWeather-stores,返回adcodeWeather长度')
  }

  const showSign = () => {
    isShow.value = false
  }
  const clearSign = () => {
    isShow.value = true
  }

  const setLocalstoreCity = (city, adcode) => {
    localstoreCity.value = JSON.parse(localStorage.getItem('savedCities'))
    // 如果本地存储没有savedCities，则返回为nll
    // 如果有，则返回数组
    if (localstoreCity.value === null) {
      localstoreCity.value = [
        {
          id: Date.now(),
          city: city,
          adcode: adcode
        }
      ]
    } else {
      // 如果有，则push
      localstoreCity.value.push({
        id: Date.now(),
        city: city,
        adcode: adcode
      })
    }
    localStorage.setItem('savedCities', JSON.stringify(localstoreCity.value))
  }

  const transmitCurCity = (city, adcode) => {
    curCity.value = city
    curAdcode.value = adcode
  }

  // 判断当前城市是否已经存储,以确定是否显示添加按钮和 “，可以通过....” 文字
  const isSavedCity = ( adcode) => {
    const savedCities = JSON.parse(localStorage.getItem('savedCities'))
    if (savedCities === null) {
      isShow_1.value = true
    } else {
      isShow_1.value =!savedCities.some((item)=> item.adcode === adcode)
    }
  }


  return {
    ipCity,
    weather,
    adcodeWeather,
    lastadcodeWeather,
    isShow,
    isShow_1,
    localstoreCity,
    curCity,
    curAdcode,
    setLocalstoreCity,
    getIpCityData,
    getWeatherData,
    showSign,
    clearSign,
    transmitCurCity,
    isSavedCity
  }
})
